/**
 * JAVACC DEMO 1.0
 */
package com.apache.seq.controller;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.seq.entity.Seq;
import com.apache.seq.manager.SeqManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * description:  序列管理的action
 *
 * @author Hou Dayu 创建时间：2016-8-12
 */
@Controller
@RequestMapping("/seq/core/")
public class SeqAction {

    private final String ADD = getPrefix() + "save";

    private final String VIEW = getPrefix() + "view";

    private final String LIST = getPrefix() + "list";

    @Autowired
    private SeqManager seqManager;

    /**
     * 功能说明：跳转到列表查询页面
     */
    @RequestMapping("list.action")
    public ModelAndView list(HttpServletRequest request) {
        return new ModelAndView(LIST);
    }

    /**
     * TODO 获取分页列表，序列管理查询
     *
     * @see com.apache.action.PlatFromAction#data(javax.servlet.http.HttpServletRequest, java.lang.String, java.lang.String)
     */
    @RequestMapping("list!data.action")
    @ResponseBody
    protected Object data(HttpServletRequest request, String page, String rows) {
        Map<String, Object> map = getParametersStartingWith(request, "filter_");
        ParamsVo<Seq> vo = new ParamsVo<Seq>();
        vo.setParams(map);
        vo.setParams("pageSize", Validator.getDefaultStr(rows, "10"));
        vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
        Page pageData = seqManager.getPageInfo(vo);

        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("total", pageData.getCount());
        mapData.put("rows", pageData.getPageObjects());
        return mapData;
    }

    /**
     * 功能说明：跳转到新增页面
     */
    @Token(save = true)
    @RequestMapping(value = "add.action", method = RequestMethod.GET)
    protected ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(ADD);
        String id = request.getParameter("id");
        Seq seq = new Seq();
        if (Validator.isNull(id)) {
            view.addObject("isAdd", "true");
        } else {
            view.addObject("isAdd", "false");
            ParamsVo vo = new ParamsVo();
            vo.setInfoId(id);
            seq = (Seq) seqManager.getInfoById(vo);
        }
        view.addObject("item", seq);
        return view;
    }

    @Token(remove = true)
    @RequestMapping(value = "/save.action", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg save(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute Seq seq) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        if (Validator.isEmpty(seq)) {
            rmsg = getResultMsg(request, "操作对象为空！");
            return rmsg;
        }
        String isAdd = Validator.getDefaultStr(request.getParameter("isAdd"), "false");
        ParamsVo<Seq> vo = new ParamsVo<Seq>();
        vo.setObj(seq);
        String id = "";
        boolean mark = false;
        if ("false".equals(isAdd)) {
            mark = seqManager.editInfo(vo);
        } else {
            vo.setMethodKey("checkUnique");
            vo.setParams("seqEname", seq.getSeqEname());
            boolean checkResult = (Boolean) seqManager.execute(vo);
            if (checkResult == true)//重复
            {
                rmsg = getResultMsg(request, "抱歉,英文序列名称" + seq.getSeqEname() + "已存在，请您重新输入!");
                return rmsg;
            }
            id = seqManager.saveInfo(vo);
        }
        if (("false".equals(isAdd) && !mark) || ("true".equals(isAdd) && Validator.isNull(id))) {
            rmsg = getResultMsg(request, "操作失败！");
        }
        return rmsg;
    }

    /**
     * 功能说明：删除功能
     *
     * @param id 删除的id
     */
    @RequestMapping(value = "/del.action")
    @ResponseBody
    public ResultMsg delete(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("T", "删除成功！");
        ParamsVo<Seq> vo = new ParamsVo<Seq>();
        if (Validator.isNotNull(id)) {
            vo.setInfoId(id);
            boolean mark = seqManager.deleteInfo(vo);
            if (!mark) {
                rmsg.setFlag("F");
                rmsg.setMsg("删除失败！");
            }
        } else {
            rmsg.setFlag("H");
            rmsg.setMsg("请不要恶意操作！");
        }
        return rmsg;
    }

    /**
     * description:  整理请求参数
     */
    @SuppressWarnings("rawtypes")
    private Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
        Enumeration paramNames = request.getParameterNames();
        Map<String, Object> params = new TreeMap<String, Object>();
        if (prefix == null) {
            prefix = "";
        }
        while ((paramNames != null) && (paramNames.hasMoreElements())) {
            String paramName = (String) paramNames.nextElement();
            if (("".equals(prefix)) || (paramName.startsWith(prefix))) {
                String unprefixed = paramName.substring(prefix.length());
                String[] values = request.getParameterValues(paramName);
                if ((values != null) && (values.length != 0)) {
                    if (values.length > 1)
                        params.put(unprefixed, values);
                    else
                        params.put(unprefixed, values[0]);
                }
            }
        }
        return params;
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     */
    private String getPrefix() {
        return "seq/core/seq-";
    }

    protected ResultMsg getResultMsg(HttpServletRequest request, String msg) {
        request.getSession().setAttribute("formToken", request.getAttribute("formToken"));
        ResultMsg rmsg = new ResultMsg("F", msg);
        return rmsg;
    }

}
